<?php
namespace information\service;

include APP_ROOT . "extends/word/WordSplit.class.php";

use herosphp\core\Loader;

class InformationService extends CommonService
{


    private $informationDao = null;
    private $informationCateDao = null;
    private $informationDataDao = null;

    public function __construct($informationModel,$adminManager, $informationCateModel,$informationDataModel) {

        $this->setModelDao(Loader::model($informationModel));
        $this->informationCateDao = Loader::model($informationCateModel);
        $this->adminManagerDao = Loader::model($adminManager);
        $this->informationDataDao = Loader::model($informationDataModel);//多表操作，初始化information_data的模型
    }

    public function getItem($conditions, $fields, $order)
    {
        //$release_status = array("未发布","已发布");
        $item = parent::getItem($conditions, $fields, $order);
        if(!$item) return NULL;
        $information_cate = $this->informationCateDao->getItem($item['cate_id']);

        //$item['release_status'] = $release_status[$item['release_status']];
        $item['information_cate_name'] = $information_cate['name'];
        $item['information_cate_id'] = $information_cate['id'];
        $item['information_cate_parent_id'] = $information_cate['parent_id'];
        $item['information_cate_summary'] = $information_cate['summary'];
        $item['information_cate_manager_id'] = $information_cate['manager_id'];
        $item['information_cate_app_id'] = $information_cate['app_id'];
        /**-- foreignitem --**/
        $admin_manager = $this->adminManagerDao->getItem($item['manager_id']);
        /**-- 获取咨询正文内容 --**/
        $information_data = $this->informationDataDao->getItem($item['id']);
        $item['tagsArr'] = json_decode($item['tags'],JSON_UNESCAPED_UNICODE);//数组形式
        $item['tagsStr'] =  implode("；",$item['tagsArr']);
        $item['content'] = $information_data['content'];
        $item['admin_manager_username'] = $admin_manager['username'];
        $item['admin_manager_password'] = $admin_manager['password'];
        $item['admin_manager_mobile'] = $admin_manager['mobile'];
        $item['admin_manager_jobno'] = $admin_manager['jobno'];
        $item['admin_manager_email'] = $admin_manager['email'];
        $item['admin_manager_name'] = $admin_manager['name'];
        $item['admin_manager_role_id'] = $admin_manager['role_id'];
        $item['admin_manager_last_login_time'] = $admin_manager['last_login_time'];
        $item['admin_manager_last_login_ip'] = $admin_manager['last_login_ip'];
        $item['admin_manager_status'] = $admin_manager['status'];
        $item['admin_manager_addtime'] = $admin_manager['addtime'];
        $item['admin_manager_updatetime'] = $admin_manager['updatetime'];
        $item['admin_manager_app_id'] = $admin_manager['app_id'];

        return $item;
    }

    /**-- daoGetItems --**/
    public function getItems($conditions, $fields, $order, $limit, $group, $having)
    {
        //按照时间进行排序
        if(!$order['addtime']){
            $order['addtime'] = -1;
        }
        //直接在这里判断状态信息，并输出对应html，避免模板麻烦的判断
        $statusHtml = array(
            "<button class='btn btn-info btn-sm disabled'>未发布</button>",
            "<button class='btn btn-sm btn-success disabled'>已发布</button>"
        );
        $items = parent::getItems($conditions, $fields, $order, $limit, $group, $having);
        if(!$items) return NULL;

        /**-- foreigncondi --**/
        $information_catecondi = array();
        foreach($items as $k => $v)
        {
            $items[$k]['tagsArr'] = json_decode($items[$k]['tags'],JSON_UNESCAPED_UNICODE);//数组形式
            $items[$k]['tagsStr'] =  implode("；",$items[$k]['tagsArr']);

            if($v['cate_id'])
            {
                $information_catecondi[] = $v['cate_id'];
            }
        }

        $information_cates = $this->informationCateDao->getItems(array('id' => array( '$in' => $information_catecondi)));

        /**-- foreigncondi --**/
        $admin_managercondi = array();
        foreach($items as $k => $v)
        {
            if($v['manager_id'])
            {
                $admin_managercondi[] = $v['manager_id'];
            }
        }

        $admin_managers = $this->adminManagerDao->getItems(array('id' => array( '$in' => $admin_managercondi)));

        /**-- foreignforeach  --**/
        foreach ($items as $k => $v)
        {
            $items[$k]['statusHtml'] = $statusHtml[$items[$k]['release_status']];
            foreach($information_cates as $kk => $vv)
            {
                if($vv['id'] == $v['cate_id'])
                {
                    $items[$k]['information_cate_name'] = $vv['name'];
                    $items[$k]['information_cate_parent_id'] = $vv['parent_id'];
                    $items[$k]['information_cate_summary'] = $vv['summary'];
                    $items[$k]['information_cate_manager_id'] = $vv['manager_id'];
                    $items[$k]['information_cate_app_id'] = $vv['app_id'];

                }
            }

            foreach($admin_managers as $kk => $vv)
            {
                if($vv['id'] == $v['manager_id'])
                {
                    $items[$k]['admin_manager_username'] = $vv['username'];
                    $items[$k]['admin_manager_password'] = $vv['password'];
                    $items[$k]['admin_manager_mobile'] = $vv['mobile'];
                    $items[$k]['admin_manager_jobno'] = $vv['jobno'];
                    $items[$k]['admin_manager_email'] = $vv['email'];
                    $items[$k]['admin_manager_name'] = $vv['name'];
                    $items[$k]['admin_manager_role_id'] = $vv['role_id'];
                    $items[$k]['admin_manager_last_login_time'] = $vv['last_login_time'];
                    $items[$k]['admin_manager_last_login_ip'] = $vv['last_login_ip'];
                    $items[$k]['admin_manager_status'] = $vv['status'];
                    $items[$k]['admin_manager_addtime'] = $vv['addtime'];
                    $items[$k]['admin_manager_updatetime'] = $vv['updatetime'];
                    $items[$k]['admin_manager_app_id'] = $vv['app_id'];

                }
            }


        }

        return $items;
    }

    /**
     * daoInsert 改写插入的方法，实现多表操作
     **/
    public function add( $data )
    {
        $tags = $data['tags'];
        $data['tags'] = $this->setTags($data['tags'],$data['title']);
        if($data['summary']=='')
        {
            $summary = strip_tags($data['content']);
            $data['summary'] =mb_substr($summary,0,100,'utf-8');
        }
        $result1 = parent::add($data);
        $result2 = $this->informationDataDao->add($data);
        if($result1 && $result2)
        {
            //新增成功之后，将标签插入数据库
            $this->addTags($tags,$result1);
            return $result1;
        }
        else
            return 0;
    }

    /**-- daoUpdate 改写插入的方法，实现多表操作 --**/
    public function update( $data,$id)
    {
        $tags  = $data['tags'];
        $da['content'] = $data['content'];
        $data['tags'] = $this->setTags($data['tags'],$data['title']);
        if($data['summary']=='')
        {
            $summary = strip_tags($data['content']);
            $data['summary'] =mb_substr($summary,0,100,'utf-8');
        }
        $result1 = parent::update($data,$id);
        $result2 = $this->informationDataDao->update($da,$id);//插入资讯内容

        if ($result1 && $result2) {
            //新增成功之后，将标签插入数据库
            $this->addTags($tags,$id);
            return $result1;
        } else {
            return 0;
        }
    }

    /**
     * 设置标签，根据用户输入的标签进行处理
     * @params tags string
     * $return tags  json
     */
    public function setTags($tags,$title)
    {
        //如果用户没有输入标签，则从标题中获取
        if(!$tags){
            $tagsArray = $this->getTagsFromTitle($title);
        }else{
            $tagsArray = explode("；",str_replace(";","；",$tags));
        }
        return json_encode($tagsArray,JSON_UNESCAPED_UNICODE);//转行成json数据
    }

    /**
     * @params tags array
     */
    public function addTags($tags,$info_id)
    {
        $informationTagsModel = Loader::model('InformationTags');
        //插入标签之前，将旧的标签删除，避免重复
        $informationTagsModel->deletes(array("information_id"=>$info_id));

        $tagsArray = explode("；",str_replace(";","；",$tags));
        if(count($tagsArray)>0)
        {
            foreach($tagsArray as $tag)
            {
                if($tag != '') {
                    $data = array('name' => $tag, 'information_id' => $info_id, 'app_id' => appId());
                    $informationTagsModel->add($data);
                }
            }
        }
    }

    /**
     * 获取标签组
     * @param int $limit 数目
     * @param string $order 排序 1=> ASC, -1 => DESC
     */
    public function getTags($limit = 10)
    {
        $app_id = appId();
        $sql = "SELECT name, COUNT(id) as sort FROM information_tags WHERE app_id='{$app_id}' GROUP BY `name` ORDER BY sort desc limit {$limit}";
        $tags =  Loader::model('InformationTags')->query($sql);
        foreach($tags as $key=>$tag)
        {
            //设置四个热门标签
            if($key<3){
                $tags[$key]['isHot'] = 1;
            }else{
                $tags[$key]['isHot'] = 0;
            }
        }
        shuffle(shuffle($tags));//shuffle对数组进行随机排序
        return $tags;
    }

    /**
     * 根据标题获取标签组
     * @param $title 标题
     * @return array
     */
    public function getTagsFromTitle($title)
    {
        return \WordSplit::split($title);
    }


}

